import cv2
import os
import time
import shutil
from config.settings import get_settings
from get_logger import get_server_logger, get_error_logger

server_logger = get_server_logger()
error_logger = get_error_logger()

class VideoRecorder:
    """
    TKD,TKD,CWD,TWD 这几个站点中, 增加实时录像功能。
    功能点：
    录像保存到本地,15分钟一个视频
    视频大小尽可能控制在1gb内 (如果严重影响视频质量,请通过讨论评估技术方案）
    当本地磁盘大小使用率达到了90%,则删除最旧的录像
    """
    def __init__(self) -> None:
        self.setting = get_settings()
        self.resolution = (1920, 1080)
        self.fps = 30
        self.codec = 'XVID'
        self.bitrate = 13499 * 1000  # bps
        self.video_duration = 15 * 60  # 15分钟
        self.max_video_size = 1 * 1024 * 1024 * 1024  # 1GB
        self.frame_count = int(self.video_duration * self.fps)  # 总帧数
        self.current_frame_count: int = 0

        # 保存视频的文件夹
        self.output_folder = os.path.join(self.setting.BASE_DIR, 'videos')
        self.fourcc = cv2.VideoWriter_fourcc(*self.codec)

        # 检查或创建输出文件夹
        if not os.path.exists(self.output_folder):
            os.makedirs(self.output_folder)

        self.out = None
        self.start_time = None
        self.previous_disk: float = 0
        self.file_name: str 

        if self.setting.VIDEO_RECORDER:
            self.init_file()

    def init_file(self):
        self.file_name = os.path.join(self.output_folder, f'{time.strftime("%Y%m%d%H%M%S")}.avi')
        
        if self.out is not None:
            self.out.release()

        self.out = cv2.VideoWriter(self.file_name, self.fourcc, self.fps, self.resolution)
        self.start_time = time.time()
        self.current_frame_count = 0
        return self.out
    
    def start(self, frame):
        # 启动视频录制
        if self.setting.VIDEO_RECORDER:
            self.record_video(frame)
            if self.check_disk_usage() >= 90:
                self.delete_oldest_video()
    
    def close(self):
        if self.out:
            self.out.release()

    def record_video(self, frame):
        if self.current_frame_count < self.frame_count:
            self.current_frame_count += 1
            self.out.write(frame)
        else:
            # 释放当前视频并开始新的
            self.out.release()
            self.init_file()

    def delete_oldest_video(self):
        try:
            # 获取所有视频文件
            video_files = [
                os.path.join(self.output_folder, f) for f in os.listdir(self.output_folder) if f.endswith('.avi')
            ]
            
            # 删除最旧的视频文件
            if len(video_files) > 1:
                oldest_file = min(video_files, key=os.path.getctime)
                if oldest_file != self.file_name:
                    os.remove(oldest_file)
                    server_logger.info(f'Deleted oldest video: {oldest_file}')
        except Exception as e:
            error_logger.error(f"Error deleting file: {e}")

    def check_disk_usage(self) -> float:
        """检查磁盘使用情况"""
        total, used, free = shutil.disk_usage('.')
        usage_percent = round((used / total) * 100, 3)
        if usage_percent != self.previous_disk:
            self.previous_disk = usage_percent
            server_logger.info(f'Disk usage: {usage_percent:.3f}%')
        return self.previous_disk